package com.deng.Service.impl;

import com.deng.Service.ColumnService;
import com.deng.Service.CommentsService;
import com.deng.Service.PaperService;
import com.deng.Service.UserService;
import com.deng.config.AllAttriOfPaper;
import com.deng.config.PaperAndColumn;
import com.deng.config.PaperAndComments;
import com.deng.config.common.Paging;
import com.deng.config.common.TimeUtil;
import com.deng.mapper.PaperMapper;
import com.deng.model.Column;
import com.deng.model.Comments;
import com.deng.model.Paper;
import com.deng.model.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.log4j.Logger;
//import com.sun.istack.internal.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author 邓小熙
 * @Date 2022/5/9 21:32
 * @Version 1.0
 */
@Service
public class PaperServiceImpl implements PaperService {
    @Autowired
    PaperMapper paperMapper;
    @Autowired
    UserService userService;
    @Autowired
    CommentsService commentsService;
    @Autowired
    ColumnService columnService;
//    Logger logger = Logger.getLogger(this.getClass());
//    Logger logger = Logger.getLogger(this.getClass());
//    Logger logger = Logger.getLogger(this.getClass());
    private static final int INIT_MARK = 1 ;
    private  static final String IS_PASS = "审核通过";
    private  static final String PASSING = "正在审核";


    /**
     * 根据id查询paper
     */
    @Override
    public Paper findPaperById(int id) {
        return paperMapper.findPaperById(id);
    }
    /**
     * 返回文章和评论的信息 按时间排序
     * @return
     */
    @Override
    public Map<String, List<PaperAndComments>> findAllPapersByTime() {
        Map<String,List<PaperAndComments>> map = Maps.newHashMap();
        List<Paper> papers = paperMapper.findAllPapersByTime();
        List<PaperAndComments> paperAndComments = paperAndCommentsList(papers);
        map.put("paper",paperAndComments);
        return map;
    }

    private List<PaperAndComments> paperAndCommentsList(List<Paper> papers) {
        ArrayList<PaperAndComments> paperAndComments = new ArrayList<>();
        for (Paper paper: papers) {
            int id = paper.getId();
            User user = paperMapper.findUserByPaperTitle(id);
            PaperAndComments paperAndComment = setValue(paper,user);
            paperAndComments.add(paperAndComment);
        }
        return paperAndComments;
    }
    //    赋值
    private PaperAndComments setValue(Paper paper,User users){
        PaperAndComments paperAndComments = new PaperAndComments();
        int count = commentsService.findCommentCountByPaperId(paper.getId());
        paperAndComments.setTitle(paper.getTitle());
        paperAndComments.setContent(paper.getContent());
        paperAndComments.setSegment(paper.getSegment());
        paperAndComments.setCount(count);
        paperAndComments.setCreate_time(paper.getCreat_time());
        paperAndComments.setPaper_image(paper.getPaper_image());
        paperAndComments.setMark(paper.getMark());
        paperAndComments.setLogin_name(users.getLogin_name());
        paperAndComments.setEmail(users.getEmail());
        paperAndComments.setHead(users.getHead());
        paperAndComments.setId(paper.getId());
        return paperAndComments;
    }
    /**
     *
     * @param id
     * @return
     */
    @Override
    public AllAttriOfPaper findAllAttriOfPaper(int id) {
        User userByPaperId = paperMapper.findUserByPaperId(id);
        String columnsById = paperMapper.findColumnsById(id);
        Paper paperById = paperMapper.findPaperById(id);
        List<Comments> commentsList = paperMapper.findCommentsById(id);
        return setValue(userByPaperId,commentsList,columnsById,paperById);
    }
    private AllAttriOfPaper setValue(User userByPaperId, List<Comments> commentsList, String columnsById, Paper paperById) {
        AllAttriOfPaper allAttriOfPaper = new AllAttriOfPaper();

        allAttriOfPaper.setColumnTitle(columnsById);
//        allAttriOfPaper.getComments(commentsList);
        List<User> list = Lists.newLinkedList();

        for (Comments c: commentsList){
            User userById = userService.findUserById(c.getComments_user());
            list.add(userById);
        }
        int count = commentsService.findCommentCountByPaperId(paperById.getId());
        allAttriOfPaper.setComments_UserMes(list);
        allAttriOfPaper.setPaper(paperById);
        System.out.println(paperById.getId());
        allAttriOfPaper.setCount(count);
        allAttriOfPaper.setComments(commentsList);
        allAttriOfPaper.setLogin_name(userByPaperId.getLogin_name());
        allAttriOfPaper.setHead(userByPaperId.getHead());
        allAttriOfPaper.setTags(paperMapper.findTagsById(paperById.getId()));
        return allAttriOfPaper;
    }
    /**
     * 查找一个月内的所有文章
     * @return
     */
    @Override
    public PageInfo<Paper> findPaperInMonth() {
        PageHelper.startPage(1, Paging.LIMIT.getValue()-5);
//        获取当前时间
        Timestamp now = new Timestamp(System.currentTimeMillis());
//      转换成date类型进行时间的加减
        Date nowDate = new Date();
        try{
            nowDate = now;
        }catch (Exception e){
            e.printStackTrace();
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(nowDate);
//        获得30天之前的日期
        calendar.add(calendar.DATE, -30);
        Date afterAdd = calendar.getTime();
//        转化为timestamps类型
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String afterAddString = simpleDateFormat.format(afterAdd);
        Timestamp end = Timestamp.valueOf(afterAddString);
        List<Paper> list = paperMapper.findPaperInMonth(end);
        return new PageInfo<>(list);
    }
    /**
     * 返回文章和评论信息 按热度排序
     * @return
     */
    @Override
    public Map<String, List<PaperAndComments>> findAllPapersByMark() {
        Map<String, List<PaperAndComments>> map = Maps.newHashMap();
        List<Paper> papers = paperMapper.findAllPapersByMark();
        List<PaperAndComments> paperAndComments = paperAndCommentsList(papers);
        map.put("paper",paperAndComments);
        return map;
    }

    /**
     * 通过ID查找文章标题
     * @param comments_paper
     * @return
     */
    @Override
    public String findPaperTitleById(int comments_paper) {
        return paperMapper.findPaperTitleById(comments_paper);
    }
    /**
     * 得到前一篇和下一片的内容
     * @param paperId
     * @return
     */
    @Override
    public Map<String, Object> findPreAndNextPage(int paperId) {
        List<Paper> paperList = paperMapper.findAllPapersByTimeNoLimit();
        Paper paper = paperMapper.findPaperById(paperId);

        int currentPaperNum = Paging.INIT.getValue() ;

        for (int i = 0 ; i <= paperList.size() ; i ++){
            if ( paperList.get(i).getId() == paper.getId() ){
                currentPaperNum = i ;
                break;
            }
        }



//        logger.info("当前页面是第"+currentPaperNum);
        boolean isPrePage = false;
        boolean isNextPage = false;
        // 前一页
        int prePaperNum = currentPaperNum - 1;
        int nextPaperNum = currentPaperNum + 1;
        String prePaperTitle;
        String segment;
        int prePaperId;
        if(prePaperNum <= 0){
            prePaperTitle="已经到头了,点击将会自动跳转到第一篇";
            prePaperId = 2 ;
            segment="";
            isPrePage = true ;
        }else {
            prePaperTitle = "上一篇："+paperList.get(prePaperNum).getTitle();
            prePaperId = paperList.get(prePaperNum).getId();
            segment = paperList.get(prePaperNum).getSegment();
        }
        Paper prePaper = new Paper();
        prePaper.setId(prePaperId);
        prePaper.setTitle(prePaperTitle);
        prePaper.setSegment(segment);

        // 下一页
        String nextPaperTitle;
        String nextSegment;
        int nextPaperId;
        if(nextPaperNum >= paperList.size()){
            nextPaperTitle = "已经到末尾了,点击将会自动跳转到第一篇";
            nextPaperId = 2;
            nextSegment = "";
            isNextPage = true;
        }else {
            nextPaperTitle = "下一篇："+paperList.get(nextPaperNum).getTitle();
            nextSegment=paperList.get(nextPaperNum).getSegment();
            nextPaperId = paperList.get(nextPaperNum).getId();
        }
        Paper nextPaper = new Paper();
        nextPaper.setId(nextPaperId);
        nextPaper.setTitle(nextPaperTitle);
        nextPaper.setSegment(nextSegment);

        Map<String,Object> map = new HashMap<>();

        map.put("prePaper",prePaper);
        map.put("nextPaper",nextPaper);
        map.put("isPrePage",isPrePage);
        map.put("isNextPage",isNextPage);
        return map;
    }
    /**
     * 个人页面所有文章,通过用户姓名查找该用户的所有文章
     * @param pageNum
     * @param search
     * @param name
     * @return
     */
    @Override
    public PageInfo<Paper> findPaperByUserName(String name, int pageNum, String search) {
        PageHelper.startPage(pageNum,Paging.LIMIT.getValue());
        PageInfo<Paper> pageInfo = new PageInfo<Paper>(paperMapper.findPaperByUserName(name,search));
        return pageInfo;
    }
    /**
     *   文章库
     * @param pageNum
     * @param search
     * @return
     */
    @Override
    public PageInfo findAllPapers(String search,int pageNum) {
        PageHelper.startPage(pageNum,Paging.LIMIT.getValue());
        PageInfo<Paper> pageInfo = new PageInfo<>(paperMapper.findAllPapers(search));
//        List<Paper> papers =  paperMapper.findAllPapers(search);
//        List<PaperAndComments> paperAndComments = paperAndCommentsList(papers);
//        return new PageInfo<>(papers);
        return pageInfo;
    }

    /**
     * 通过用户统计该用户文章数量
     * @param name
     * @return
     */
    @Override
    public int findCountOfPaperByUser(String name) {
        return paperMapper.findCountOfPaperByUser(name);
    }

    @Override
    public List findAllPapers(String search) {
        List<Paper> papers =  paperMapper.findAllPapers(search);
        return paperAndCommentsList(papers);
    }
    /**
     * 根据文章名字查询文章
     * @param name
     * @param pageNum
     * @return
     */
    @Override
    public Map<String,Object> findPaperByUser(String name,String pageNum) {
        int limit = Paging.LIMIT.getValue() ;
        int pageNum1 = Integer.parseInt(pageNum);
        Map<String,Object> map = Maps.newHashMap();

        int count = paperMapper.findCountOfPaperByUser(name);
        List<Paper> papers = paperMapper.findPaperByUser(name,(pageNum1-1) * limit,limit);
        List<PaperAndColumn> list = setValueToPaperAndColumn(papers);
        map.put("code",0);
        map.put("mes","");
        map.put("count",count);
        map.put("data",list);
        return map;
    }

    private List<PaperAndColumn> setValueToPaperAndColumn(List<Paper> papers) {
        List<PaperAndColumn> li1 = Lists.newLinkedList();
        for (Paper p:papers
        ) {
            Column column = columnService.findColumnByPaperId(p.getId());
            PaperAndColumn paperAndColumn = new PaperAndColumn();
            paperAndColumn.setPaperId(p.getId());
            paperAndColumn.setCreateTime(p.getCreat_time());
            paperAndColumn.setIs_pass(p.getIs_pass());
            paperAndColumn.setPaperTitle(p.getTitle());
            columnIsNull(column,paperAndColumn);
            li1.add(paperAndColumn);
        }
        return li1;
    }

    private Boolean columnIsNull(Column column,PaperAndColumn paperAndColumn){
        if(column == null){
            paperAndColumn.setTheme("暂无");
        }
        else {
            paperAndColumn.setTheme(column.getTitle());
        }
        return true;
    }
    /**
     * 更新文章内容
     * @param id
     * @param content
     * @return
     */
    @Override
    public int updatePaperContentById(String content, String id) {
        int id1 = Integer.parseInt(id);
        return paperMapper.updatePaperContentById(content,id1);
    }
    @Override
    public int deletePaperByPaperId(int id) {
        paperMapper.deletePaperInCoulmn(id);
        return paperMapper.deletePaperByPaperId(id);
    }

    /**
     * 后台文章管理的数据
     * @param pageNum 当前页数
     * @param interval 时间选择
     * @param search 查询关键字
     * @return所有文章的数据
     */
    @Override
    public Map<String, Object> findPapers(int pageNum,String search,String interval) throws NumberFormatException {
        int limit = Paging.LIMIT.getValue();
        int count = paperMapper.findAllPaperCount();
        // 时间间隔天数
        int inter = 0;
//        logger.info("search:" +search);
        List<Paper> list = null;
        Map<String, Object> map = new HashMap<>();
        if(interval != null && !"".equals(interval)) {
            inter = Integer.parseInt(interval);
            //获得当前时间
            Timestamp now = new Timestamp(System.currentTimeMillis());
            //转换成data类型进项时间的加减
            Date nowDate = new Date();
            try {
                nowDate = now;
            } catch (Exception e) {
                e.printStackTrace();
            }
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(nowDate);
            calendar.add(calendar.DATE, -inter);
            Date afterAdd = calendar.getTime();
            // 转化为timestamps类型
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String afterAddString = simpleDateFormat.format(afterAdd);
            Timestamp end = Timestamp.valueOf(afterAddString);
            // 几天前的时间 end
            list = paperMapper.findPapers((pageNum - 1) * limit, limit, search, now, end);
        } else {
            list = paperMapper.findPapers((pageNum - 1) * limit, limit, search, null, null);
        }
//        int count = list.size();
        map.put("code",0);
        map.put("mes","");
        map.put("count",count);
        map.put("data",list);
        map.put("limit",limit);
        return map;
    }
    /**
     * 更改文章状态执行方法
     * @param review 输入状态 string类型
     * @param id 文章id
     * @return
     */
    @Override
    public int updatePaperStatus(int id, String review) {
        return paperMapper.updataPaperStatus(id,review);
    }

    @Override
    public int findAllPaperCount() {
        return paperMapper.findAllPaperCount();
    }

//    @Override
//    public PageInfo<Paper> findAllPapersByPageInfo(int pageNum) {
//        PageHelper.startPage(pageNum, Paging.LIMIT.getValue());//ConstantUtils.PAGE_SIZE 是设置每页显示条数
//        List<User> list  = userMapper.getList();//获取数据集合
//        PageInfo<User> pageInfo = new PageInfo<>(list, ConstantUtils.NAVIGATE_PAGENUM);//ConstantUtils.NAVIGATE_PAGENUM 是分页中间显示的那个玩意
//        return pageInfo;
//    }

    /**
     * 新建文章
     * @param title
     * @param content
     * @param segment
     * @param name
     * @return
     */
    @Override
    public int insertPaper(String title, String content, String segment, String name,String paper_image) {
//        需要把name通过usermapper转为id插入
        int author = userService.findAuthorByName(name);
        Timestamp createTime = TimeUtil.setCurrentTime();
        return paperMapper.insertPaper(title,content,createTime,author,segment,paper_image,INIT_MARK,PASSING);
    }
    /**
     * 根据信息查id
     * @param title
     * @param segment
     * @param name
     * @return
     */
    @Override
    public int findPaperId(String title, String segment,String name) {
        int author = userService.findAuthorByName(name);
        return paperMapper.findPaperId(title,segment,author);
    }
}
